//
//  VideoGenerateVC.swift
//  NDAi
//
//  Created by 丸子 on 2024/6/21.
//

import UIKit
import IQKeyboardManagerSwift

class VideoGenerateVC: BaseViewController {
    let viewModel = VideoViewModel()
    let disposeBag = DisposeBag()
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(cellWithClass: VideoGenerateTitleCell.self)
        tableView.register(cellWithClass: VideoGenerateResultCell.self)
        tableView.register(cellWithClass: HomeVideoClassCell.self)
        tableView.rowHeight = UITableView.automaticDimension
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 72, right: 0)
        return tableView
    }()
    
    private lazy var descGenerateBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "生成"
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.titleColorForNormal = .white
        button.allRound(24)
        button.backgroundColor = UIColor(hexString: "#25262B")
        button.isHidden = false
        return button
    }()
    
    private lazy var resetBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.normalBackgroundImage = UIImage(named: "icon_paninting_reset")
        button.isHidden = true
        return button
    }()
    
    private lazy var saveBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "生成视频"
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.backgroundColor = UIColor(hexString: "#25262B")
        button.allRound(24)
        button.isHidden = true
        return button
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = true
        self.updateRight()
        RequestService.instance.getUserInfo()
        if self.viewModel.videoList.count == 0{
            self.viewModel.getHomeVideoList()
        }

    }
//    private lazy var footerView: UIView = {
//        let view = UIView()
//        view.backgroundColor = .clear
//        return view
//    }()
    
    lazy var tipsLb: UILabel = {
        let label = UILabel()
        label.font = UIFont.pingFangSCRegular(ofSize: 11)
        label.textColor = Theme.color.text_d2
        label.numberOfLines = 0
        label.text = ""
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hexString: "#F3F2F7")
        self.navigationItem.title = "一键成片"
        self.view.addSubview(tableView)
        self.view.addSubview(descGenerateBtn)
        self.view.addSubviews([resetBtn, saveBtn])
        tableView.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(self.safeBottom)
        }
        
        descGenerateBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.safeBottom).offset(-10)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(48)
        }
        
        resetBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.safeBottom).offset(-10)
            make.leading.equalToSuperview().offset(15)
            make.height.equalTo(48)
            make.width.equalTo(110)
        }
        
        saveBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.safeBottom).offset(-10)
            make.leading.equalTo(resetBtn.snp.trailing).offset(10)
            make.trailing.equalToSuperview().offset(-15)
            make.height.equalTo(48)
        }
        
        
//        self.tableView.tableFooterView = self.footerView
//        self.footerView.addSubview(tipsLb)
    
        
        saveBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            if self.viewModel.messageStr.count > 20 {
                let vc = VideoStyleViewController()
                vc.message = self.viewModel.messageStr
                vc.titleStr = self.viewModel.keyword
                self.navigationController?.pushViewController(vc)
                self.clearData()
            }
        }
         
        let leftBtn = UIButton(type: .custom)
        leftBtn.setImage(UIImage(named: "icon_videoH_history"), for: .normal)
        let leftItem = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = leftItem
        
        leftBtn.setClosureTouchUpInside_k { [weak self] in
            if !Appearance.shared.isLoign {
                GlobalRx.loginSubject.onNext(())
                return
            }
            let vc = VideoHistoryViewController()
            self?.navigationController?.pushViewController(vc)
        }
        
        self.descGenerateBtn.setClosureTouchUpInside_k { [weak self] in
            self?.showBuyVideo()
        }
        
        self.viewModel.messageEventSubject.subscribe(onNext: { [weak self] code, msg in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.tableView.reloadData()
                if code == 1 { //滚动到底部
                    self.scrollToBottom()
                }else if code == -1 {//隐藏键盘
                    kHideKeyboard()
                }else if code == 2 {
                    self.resetBtn.isHidden = false
                    self.saveBtn.isHidden = false
                    self.descGenerateBtn.isHidden = true
                }
                if let msg = msg {
                    NDProgressHUD.show(message: msg)
                }
            }
        }).disposed(by: disposeBag)
        
        resetBtn.setClosureTouchUpInside_k { [weak self] in
            self?.clearData()
        }
        
        
        self.getDesc()
        self.updateRight()
        let rightItem = UIBarButtonItem(customView: self.rightBtn)
        self.navigationItem.rightBarButtonItem = rightItem
        rightBtn.setClosureTouchUpInside_k { [weak self] in
            if Appearance.shared.accoutModel != nil {
                if Appearance.shared.accoutModel?.userOtherInfo?.is_vip == 1 {
                    let vc = DiamondBuyViewController()
                    self?.navigationController?.pushViewController(vc, animated: true)
                }else {
                    let vc = SubscribeViewController()
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
            }else {
                GlobalRx.loginSubject.onNext(())
            }
        }
        
        viewModel.getHomeVideoList()
        
        viewModel.reloadDataSubject.subscribe(onNext: { [weak self] in
            guard let self = self else { return }
            self.tableView.reloadData()
            if self.viewModel.videoList.count > 0 {
                let userDefaults = UserDefaults.standard
//                userDefaults.set(false, forKey: firstLaunchVideoGuideKey)
                if userDefaults.bool(forKey: firstLaunchVideoGuideKey) == false {
                    userDefaults.set(true, forKey: firstLaunchVideoGuideKey)
                    self.videoGuide()
                }
            }
        }).disposed(by: disposeBag)
    }
    var xrect:CGRect?
    @objc func videoGuide(){
        let videoGuideView = HomeVideoGuideView()
        if self.tipsLb.text?.count ?? 0 > 0 {
            
            let rect = getSectionPosition(section: 1) ?? CGRect.zero
            if xrect == nil {
                xrect = rect
                self.perform(#selector(self.videoGuide), with: nil, afterDelay: 0.3)
                return
            }
            if let x = xrect, x.origin.y == rect.origin.y {
                xrect = rect
                self.perform(#selector(self.videoGuide), with: nil, afterDelay: 0.3)
                return
            }
            videoGuideView.initUI(rect: rect)
            Appearance.addViewToWindow(videoGuideView)
            videoGuideView.nextGuideBag = { [weak self] in }
        }else {
            self.perform(#selector(self.videoGuide), with: nil, afterDelay: 0.3)
        }
    }
    
    func getSectionPosition(section:Int) -> CGRect? {
        if tableView.numberOfSections > section {
            let sectionRect = tableView.rectForHeader(inSection: section)
            let convertedRect = tableView.convert(sectionRect, to: tableView.superview)
            return convertedRect
        }
        return nil
    }
    func clearData(){
        self.resetBtn.isHidden = true
        self.saveBtn.isHidden = true
        self.descGenerateBtn.isHidden = false
        self.viewModel.messageStr = "输入主题开始生成吧～"
        self.tableView.reloadData()
    }
    
    lazy var rightBtn:UIButton = {
        let rightBtn = UIButton(type: .custom)
        rightBtn.backgroundColor = UIColor(hexString: "#464957")
        rightBtn.allRound(12)
        rightBtn.titleLabel?.font = UIFont.pingFangSCRegular(ofSize: 15)
        rightBtn.layoutButtonWithEdgeInsetsStyle(.Left, space: 5)
        rightBtn.contentEdgeInsets = UIEdgeInsets(top: 2, left: 12, bottom: 3, right: 12)
        return rightBtn
    }()
    
    func updateRight(){
        if Appearance.shared.accoutModel?.userOtherInfo?.is_vip == 1 {
            rightBtn.setImage(UIImage(named: "icon_diamond_mix"), for: .normal)
            rightBtn.setTitle("充值", for: .normal)
        }else {
            rightBtn.setImage(UIImage(named: "icon_home_sub"), for: .normal)
            rightBtn.setTitle("订阅", for: .normal)
        }
    }
    
    func showBuyVideo(){
        if !Appearance.shared.isLoign {
            GlobalRx.loginSubject.onNext(())
            return
        }
        if self.viewModel.keyword.count <= 0 {
            NDProgressHUD.showSuccess(title: "", subtitle: "请输入你想问的问题!")
            return
        }
        if let score = Appearance.shared.accoutModel?.userOtherInfo?.score {
            if score < Int(self.lose) {
                self.nomoreScore(score: score)
            }else {
                self.generatePOPView(score: score)
            }
        }
    }
    
    func nomoreScore(score:Int){
        let user = Appearance.shared.accoutModel
        if user?.userOtherInfo?.is_vip == 1 {
            let view = VideoTopupView()
            Appearance.addViewToWindow(view)
            view.chooseDone = { [weak self] in
                let vc = DiamondBuyViewController()
                self?.navigationController?.pushViewController(vc)
            }
        }else {
            let view = VideoTopupView()
            view.titleLabel.text = "钻石余额不足, 升级会员可获增钻石"
            view.confirmButton.titleForNormal = "立即升级"
            Appearance.addViewToWindow(view)
            view.chooseDone = { [weak self] in
                let vc = SubscribeViewController()
                self?.navigationController?.pushViewController(vc)
            }
        }
    }
    
    func generatePOPView(score:Int){
        let view = VideoBuyView()
        Appearance.addViewToWindow(view)
        view.initViews(money: "\(score)", lose: "\(self.lose)", title: "生成视频将花费\(self.lose)钻石")
        view.chooseDone = { [weak self] in
            self?.sendMessage()
        }
    }
    
    func sendMessage(){
        if self.viewModel.keyword.count > 0 {
            kHideKeyboard()
            self.viewModel.checkWords(message: self.viewModel.keyword)
        }else {
            NDProgressHUD.showSuccess(title: "", subtitle: "请输入你想问的问题!")
        }
    }
    var previousOffset: CGFloat = 0
    
    func scrollToBottom() {
        tableView.reloadData()
        do {
            let indexPath = IndexPath(row: 1, section: 0)
            tableView.scrollToRow(at: indexPath, at: .bottom, animated: false)
        } catch {
            // Handle any potential exceptions here
        }
    }
    var lose:Int = 0
    func getDesc(){
        RequestService.instance.videoDescs { [weak self] dict in
            self?.lose = dict["score"] as? Int ?? 0
            self?.tipsLb.text = dict["descs"] as? String ?? ""
        }
    }
}
extension VideoGenerateVC: UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            if self.viewModel.messageStr == "输入主题开始生成吧～" {
                return 1
            }else {
                return 2
            }
        }else {
            return self.viewModel.videoList.count >= 1 ? 1 : 0
        }
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withClass: VideoGenerateTitleCell.self, for: indexPath)
                cell.chooseDesc = { [weak self]  text in
                    self?.viewModel.keyword = text
                }
                cell.descTextView.text = self.viewModel.keyword
                return cell
            }else {
                let cell = tableView.dequeueReusableCell(withClass: VideoGenerateResultCell.self, for: indexPath)
                cell.contentLb.text = self.viewModel.messageStr
                cell.copyBtn.setClosureTouchUpInside_k { [weak self] in
                    UIPasteboard.general.string = self?.viewModel.messageStr ?? ""
                    NDProgressHUD.show(message: "复制成功")
                }
                return cell
            }
        }else {
            let cell = tableView.dequeueReusableCell(withClass: HomeVideoClassCell.self, for: indexPath)
            cell.setup(list: self.viewModel.videoList)
            return cell
        }
      
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                return 50 + GET_WIDTH(W: 80)
            }else {
                let text = self.viewModel.messageStr.height(withConstrainedWidth: SCREEN_WIDTH - 64, font: UIFont.pingFangSCRegular(ofSize: 13))
                return 74 + text
            }
        }else {
            let height = (SCREEN_WIDTH - 52) / 2
            return 96 + height
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0 {
            let view = UIView()
            view.backgroundColor = .clear
            
            view.addSubview(tipsLb)
            tipsLb.snp.makeConstraints { make in
                make.top.equalTo(16)
                make.leading.equalTo(16)
                make.trailing.equalTo(-16)
            }
            return view
        }else {
            return UIView()
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            if let text = tipsLb.text {
                let getHeight = text.sizeOfString(UIFont.pingFangSCRegular(ofSize: 11))
                return getHeight.height + 16
//                self.footerView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: getHeight.height + 16)
            }
            return 0.01
        }else {
            return 0.01
        }
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let currentOffset = scrollView.contentOffset.y
        let scrollDistance = abs(currentOffset - previousOffset)

        if scrollDistance > 30 {
            kHideKeyboard()
            previousOffset = currentOffset // 更新 previousOffset
        }
    }
}
